package com.software.project_view.utils;

import com.google.gson.GsonBuilder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static java.nio.charset.StandardCharsets.UTF_8;

public class StringUtil {

    public static String applySha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes(UTF_8));
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getJson(Object o) {
        return new GsonBuilder().setPrettyPrinting().create().toJson(o);
    }

    public static String getDifficultyString(int difficulty) {
        return new String(new char[difficulty]).replace('\0', '0');
    }

    public static byte[] SHA2(byte[] b1, byte[] b2, byte[] b3, byte[] b4) {
        try {
            MessageDigest sha2 = MessageDigest.getInstance("SHA-256");
            byte[] b = new byte[b1.length + b2.length + b3.length + b4.length];
            System.arraycopy(b1, 0, b, 0, b1.length);
            System.arraycopy(b2, 0, b, b1.length, b2.length);
            System.arraycopy(b3, 0, b, b1.length + b2.length, b3.length);
            System.arraycopy(b4, 0, b, b1.length + b2.length + b3.length, b4.length);
            return sha2.digest(b);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] SHA2(byte[] b) {
        try {
            MessageDigest sha2 = MessageDigest.getInstance("SHA-256");
            return sha2.digest(b);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
